import {
  Injectable,
  CanActivate,
  ExecutionContext,
  Logger,
} from '@nestjs/common';
import { AuthConfig, Utils } from '../index';

const HEADER_TOKEN = AuthConfig.HEADER_TOKEN;
const HEADER_ACCESS_TOKEN = AuthConfig.HEADER_ACCESS_TOKEN;

@Injectable()
export class AuthGuard implements CanActivate {
  constructor() {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();
    console.log(request.headers);
    const authData: any = {
      token: request.headers[HEADER_TOKEN],
      access_token: request.headers[HEADER_ACCESS_TOKEN],
    };
    if (!authData.token && !authData.access_token) return false;
    Logger.log(JSON.stringify(authData));
    try {
      const payload = await Utils.JwtUtils.check(
        authData.access_token,
        authData.token,
      );
      console.log(payload);
      request.user = payload; // 附加用户信息到请求对象
      return true;
    } catch (e) {
      Logger.error(e);
      return false;
    }
  }
}
